//
//  GSStrategyFocusCollectionViewController.m
//  GameSky
//
//  Created by lanou on 16/1/11.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSStrategyFocusCollectionViewController.h"
#import "GSSearchViewController.h"
#import "GSStrategyFocusCell.h"
#import "GSStrategyHeaderView.h"
#import "GSStrategyFooterView.h"

@interface GSStrategyFocusCollectionViewController () <UIScrollViewDelegate>

@property (nonatomic, strong) NSMutableArray *listDataArray;

@property (nonatomic, assign) NSInteger pageIndex;// 刷新个数
@property (nonatomic, assign) BOOL isRefreshing;// 刷新状态

@end

@implementation GSStrategyFocusCollectionViewController

- (NSMutableArray *)listDataArray
{
    if (!_listDataArray) {
        _listDataArray = [NSMutableArray array];
    }
    return _listDataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageIndex = 1;
    _isRefreshing = NO;
    
    // 设置CollecionView属性;
    [self setupCollectionView];
    
    [self loadData];
    [self refreshData];
}

/**
 *  数据加载
 */
- (void)loadData
{
    NSMutableDictionary *paraDict = [NSMutableDictionary dictionary];
//    paraDict[@"deviceType"] = @"iPhone5,3";
//    paraDict[@"deviceId"] = @"17E14E61-4069-4736-992D-EE596A7AECBC";
//    paraDict[@"os"] = @"iOS";
//    paraDict[@"osVersion"] = @"8.4";
//    paraDict[@"app"] = @"GSApp";
//    paraDict[@"appVersion"] = @"2.1.0";
    paraDict[@"request"] = @{@"type":@0, @"pageIndex":@(_pageIndex), @"pageCount":@"20"};
//    NSData *data = [NSJSONSerialization dataWithJSONObject:paraDict options:NSJSONWritingPrettyPrinted error:nil];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://appapi2.gamersky.com/v2/strategy"] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:20];
//    [request setHTTPMethod:@"POST"];
//    [request setHTTPBody:data];
//    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        if (data) {
//            NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
//            NSArray *resultArray = dataDict[@"result"];
//            for (NSDictionary *subDict in resultArray) {
//                GSStrategyMainModel *model = [[GSStrategyMainModel alloc] init];
//                [model setValuesForKeysWithDictionary:subDict];
//                [self.listDataArray addObject:model];
//            }
//            // 刷新界面;
//            [self.collectionView reloadData];
//        }        
//    }];
//    [task resume];
    [GSNetworkManager requestWithUrlStr:@"http://appapi2.gamersky.com/v2/strategy" paraDict:paraDict method:POST success:^(NSURLResponse *response, NSData *data) {
        if (data) {
            NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            
            // 下拉刷新清空模型数组;
            if (_pageIndex == 1) {
                [self.listDataArray removeAllObjects];
            }
            
            NSArray *resultArray = dataDict[@"result"];
            for (NSDictionary *subDict in resultArray) {
                GSStrategyMainModel *model = [[GSStrategyMainModel alloc] init];
                [model setValuesForKeysWithDictionary:subDict];
                [self.listDataArray addObject:model];
            }
            // 结束刷新;
            _isRefreshing = NO;
            [self.collectionView.mj_header endRefreshing];
            [self.collectionView.mj_footer endRefreshing];
            
            
            // 刷新界面;
            [self.collectionView reloadData];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

/**
 *  数据刷新
 */
- (void)refreshData
{
    // 下拉刷新
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _isRefreshing = YES;
        // 下拉刷新重新加载数据;
        _pageIndex = 20;
        [self loadData];
    }];
    
    // 上拉刷新
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _isRefreshing = YES;
        // 上拉刷新依次叠加数据;
        _pageIndex = 20;
        [self loadData];
    }];
}

/**
 *  添加CollectionView
 */
- (void)setupCollectionView
{
    // 夜间模式
    self.collectionView.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
    // 注册自定义单元和表头;
    [self.collectionView registerClass:[GSStrategyFocusCell class] forCellWithReuseIdentifier:@"GSStrategyFocusCell"];
    [self.collectionView registerClass:[GSStrategyHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GSStrategyHeaderView"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.listDataArray.count;
}
// 设置单元格;
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    GSStrategyFocusCell *cell =
    [collectionView dequeueReusableCellWithReuseIdentifier:@"GSStrategyFocusCell" forIndexPath:indexPath];
    cell.model = self.listDataArray[indexPath.row];
    return cell;
}
// 设置表头表尾;
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        GSStrategyHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GSStrategyHeaderView" forIndexPath:indexPath];
        [headerView.searchBtn addTarget:self action:@selector(searchBtnClick) forControlEvents:(UIControlEventTouchUpInside)];
        return headerView;
    }
    return nil;
}

- (void)searchBtnClick
{
    UINavigationController *naviC = [[UINavigationController alloc] initWithRootViewController:[[GSSearchViewController alloc] init]];
    [self presentViewController:naviC animated:YES completion:nil];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    GSStrategyMainModel *model = self.listDataArray[indexPath.row];
    if ([_delegate respondsToSelector:@selector(setStrategyDetailViewWithModel:)]) {
        [_delegate setStrategyDetailViewWithModel:model];
    }    
}

/**
 *  根据ScrollView纵向偏移量弹出搜索框;
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y < -22 && scrollView.contentOffset.y > -44) {
        [scrollView setContentOffset:CGPointMake(0, -44)];
    }
}

#pragma mark <UICollectionViewDelegate>

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/

@end
